// render函数 负责将一个vnode渲染到dom节点
// h函数 创建vnode
import { h, render, reactive } from 'vue'
import type { CreateMessageProps, MessageContext } from './types'
import MessageConstructor from './Message.vue'
// 创建数组 = 存放组件的实例
const instances: MessageContext[] = reactive([])
let seed = 1
export const createMessage = (props: CreateMessageProps) => {
    const id = `message_${seed++}`
    // 1. 创建dom元素
    const container = document.createElement('div')

    // 移除节点 
    const destroy = () => {
        const idx = instances.findIndex(instance => instance.id)
        if (idx === -1) return
        instances.splice(idx, 1)
        render(null, container)
    }

    const newProps = {
        ...props,
        onDestroy: destroy,
        id
    }
    // 2. 创建虚拟dom节点
    const vnode = h(MessageConstructor, newProps)
    console.log('vnode', vnode);


    // 3. 渲染dom
    render(vnode, container)
    // 4. 添加到页面中
    document.body.appendChild(container.firstElementChild!)

    // 创建组件实例
    const vm = vnode.component!
    const instance = {
        id,
        vnode,
        props: newProps,
        vm
    }
    instances.push(instance)
    return instance
}

// 可以获取最后一个实例
export const getLastInstance = () => {
    return instances[instances.length - 1]
}

// 获取上一个实例最下面的坐标位置
export const getLastBottomOffset = (id: string) => {
    const idx = instances.findIndex(instance => instance.id === id)
    console.log('idx', idx, id, instances.length);

    if (idx <= 0) {
        return 0
    } else {
        // 获取上一项
        const prev = instances[idx - 1]
        return prev.vm.exposed!.bottomOffset.value
    }
}